package redis

import (
	"fmt"
	"github.com/go-redis/redis"
	"github.com/spf13/viper"
	"shop-api/pkg/log"
	"time"
)

func withClient(hand func(rdb *redis.Client) error) error {
	addr := fmt.Sprintf("%v:%v", viper.GetString("redis.host"), viper.GetString("redis.port"))
	client := redis.NewClient(&redis.Options{
		Addr: addr,
		DB:   viper.GetInt("redis.db"), // use default DB
	})
	defer func() {
		err := client.Close()
		if err != nil {
			log.LogError(err)
		}
	}()
	_, err := client.Ping().Result()
	if err != nil {
		log.LogError(err)
		return err
	}
	return hand(client)

}

func Get(key string) (val string, err error) {
	err = withClient(func(rdb *redis.Client) error {
		val, err = rdb.Get(key).Result()
		return err
	})
	return
}

func Set(key, val string, exp time.Duration) error {
	return withClient(func(rdb *redis.Client) error {
		_, err := rdb.Set(key, val, exp).Result()
		return err
	})
}

func Exist(key string) (val bool, err error) {
	err = withClient(func(rdb *redis.Client) error {
		res, err := rdb.Exists(key).Result()
		if err != nil {
			return err
		}
		if res > 0 {
			val = true
		}
		return nil
	})
	return
}
